package com.aspire.nm.component.cmppserver.filter.coder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.springframework.stereotype.Service;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppPacket;
import com.aspire.nm.component.cmppserver.filter.coder.packet.PacketException;

@Service
public class CmppProtocolEncoder implements ProtocolEncoder {
	/**
	 * 抛出异常filter和handler中的exceptionCaught都会捕获
	 * @throws PacketException 
	 */
	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws PacketException {

		CmppPacket cmppPk = (CmppPacket) message;
		byte[] ret = cmppPk.pack();
		
		IoBuffer buf = IoBuffer.allocate(ret.length, false);
		buf.setAutoExpand(true);
		buf.put(ret);

		buf.flip();
		out.write(buf);
	}

	@Override
	public void dispose(IoSession session) throws Exception {}

}
